using System;
using Microsoft.Practices.EnterpriseLibrary.Configuration.Design;
using YB.EnterpriseLibrary.XSLTManager.Configuration;

namespace YB.EnterpriseLibrary.XSLTManager.Configuration.Design
{
    public class XSLTConfigurationDesignManager : ConfigurationDesignManager
    {
        public override void Register(IServiceProvider serviceProvider)
        {
            XSLTNodeMapRegistrar nodeRegistrar = new XSLTNodeMapRegistrar(serviceProvider);
            nodeRegistrar.Register();
            XSLTCommandRegistrar cmdRegistrar = new XSLTCommandRegistrar(serviceProvider);
            cmdRegistrar.Register();
        }

        protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, System.Configuration.ConfigurationSection section)
        {
            if (null != section)
            {
                XSLTManagerSettingsNodeBuilder builder = new XSLTManagerSettingsNodeBuilder(serviceProvider, (XSLTManagerSettings)section);
                XSLTManagerSettingsNode xsltManagerNode = builder.Build();
                SetProtectionProvider(section, xsltManagerNode);

                rootNode.AddNode(xsltManagerNode);
            }
        }

        protected override ConfigurationSectionInfo GetConfigurationSectionInfo(IServiceProvider serviceProvider)
        {
            ConfigurationNode rootNode = ServiceHelper.GetCurrentRootNode(serviceProvider);
            XSLTManagerSettingsNode node = null;
            if (rootNode != null) node = (XSLTManagerSettingsNode)rootNode.Hierarchy.FindNodeByType(rootNode, typeof(XSLTManagerSettingsNode));
            XSLTManagerSettings xsltSection;
            if (node == null)
            {
                xsltSection = null;
            }
            else
            {
                XSLTManagerSettingsBuilder builder = new XSLTManagerSettingsBuilder(serviceProvider, node);
                xsltSection = builder.Build();
            }
            string protectionProviderName = GetProtectionProviderName(node);

            return new ConfigurationSectionInfo(node, xsltSection, XSLTManagerSettings.SectionName, protectionProviderName);
        }

    }
}
